#!/usr/bin/make -f

DOCKER_REPO:=tanosi/
SCRIPTDIR:=$(dir $(abspath $(lastword $(MAKEFILE_LIST))))
BUILDROOT:=$(abspath $(SCRIPTDIR)/root)

# Sanity checks
ifeq ("$(SCRIPTDIR)","$(CURDIR)")
$(error Please run ./packaging/build inside of the project source directory)
endif

#
# List of supported OS
#

DEBIAN:=
UBUNTU:=ubuntu-xenial-amd64 ubuntu-xenial-i386

DEBS:=$(DEBIAN) $(UBUNTU)

# CI values
CI_COMMIT:=
CI_TAG:=
CI_BUILD:=

## Defaults
PROJECT=$(notdir $(basename ${CURDIR}))
PROJECT_PREFIX:=
VERSION=$(shell cat VERSION)
ifneq ($(CI_TAG), )
NIGHTLY=0
else
NIGHTLY=1
endif

-include $(SCRIPTDIR)/projects/$(PROJECT).mk

# Debian overrides
DEB_VERSION=$(VERSION)
ifneq ($(CI_TAG), )
DEB_RELEASE=1
else ifneq ($(CI_BUILD), )
DEB_RELEASE=0~build$(CI_BUILD)
else
DEB_RELEASE=0
endif

# Apple overrides
APPLE_VERSION=$(VERSION)
ifneq ($(CI_BUILD), )
APPLE_RELEASE=_build$(CI_BUILD)
else
APPLE_RELEASE=
endif

NAME=$(PROJECT_PREFIX)$(PROJECT)-$(VERSION)
DATE=$(shell date +%Y-%m-%d)
TARBALL=$(NAME).tar.gz
TARBALL_EXTRA_ARGS:=

# get os-dist from target name
define osdist
$(shell echo $1| sed -n 's/.*\/\([a-z]*\)-\([_a-z0-9\-]*\).*/\2/p')
endef

define ostarget
$(shell echo $1| sed -n 's/\([_a-z0-9\-]*\)-\([_a-z0-9\-]*\)-\([_a-z0-9\-]*\)/\2/p')
endef

define osarch
$(shell echo $1| sed -n 's/\([_a-z0-9\-]*\)-\([_a-z0-9\-]*\)-\([_a-z0-9\-]*\)/\3/p')
endef

define builderu
$(shell echo $1| sed -n 's/.*\/\([a-z]*\)-\([_a-z0-9\-]*\).*/\1/p' | tr a-z A-Z)
endef

define builder
$(shell echo $1| sed -n 's/.*\/\([a-z]*\)-\([_a-z0-9\-]*\).*/\1/p')
endef

$(info -------------------------------------------------------------------)
$(info Building $(PROJECT) $(VERSION))
$(info -------------------------------------------------------------------)

##
## Common rules
##

# Build all
all: $(DEBS)

TAR:=tar
ifneq ($(strip $(shell which gtar)), )
	TAR=gtar
endif

$(BUILDROOT)/files:
	@mkdir -p $(dir $@)
	git ls-files >> $@

# Create tarball in buildroot
$(BUILDROOT)/$(TARBALL): $(BUILDROOT)/files
	@echo "-------------------------------------------------------------------"
	@echo "Creating source tarball"
	@echo "-------------------------------------------------------------------"
	$(TAR) \
		--exclude=.git --exclude='.gitignore' --exclude='.gitmodules' \
		--exclude=packaging \
		--exclude=debian --exclude=rpm \
		$(TARBALL_EXTRA_ARGS) \
		--transform="s,,$(NAME)/,S" \
		--owner=root --group=root \
		-T $< --show-transformed \
		-czvf $@

# Copy tarball to buildroot/$OS-$DIST chroot
$(BUILDROOT)/%/$(TARBALL): $(BUILDROOT)/$(TARBALL)
	cp -pf $< $@

# Copy builder.mk to buildroot/$OS-$DIST
$(BUILDROOT)/%/Makefile:
	@mkdir -p $(dir $@)
	cp -pf $(SCRIPTDIR)/types/$(call builder,$@).mk $@

# Build packages using Docker in buildroot/$OS-$DIST/
$(BUILDROOT)/%/.build: $(BUILDROOT)/%/$(TARBALL) \
                       $(BUILDROOT)/%/Makefile
	@echo "-------------------------------------------------------------------"
	@echo "Building packages"
	@echo "-------------------------------------------------------------------"
	rm -rf $@
	cd $(dir $@) && \
	ls -l && \
	docker run \
		-ti \
		--volume $$(pwd):$$(pwd) \
		--volume $(HOME)/.ccache:/ccache \
		-e CCACHE_DIR=/ccache \
		--workdir $$(pwd) \
		--rm=true $(DOCKER_REPO)$(call osdist,$@) \
		make PROJECT=$(PROJECT_PREFIX)$(PROJECT) NAME=$(NAME) \
	         TARBALL=$(TARBALL) TARGET=$(call ostarget,$(call osdist,$@)) \
	         VERSION=$($(call builderu,$@)_VERSION) \
	         RELEASE=$($(call builderu,$@)_RELEASE) \
			 NIGHTLY=$(NIGHTLY) COMMIT=$(CI_COMMIT)
	@echo "Successfully build $(PROJECT) for $@"
	ls -1sh $(dir $@)/results/
	test -f $(dir $@)/results/.done

# Build packages directly in current shell
$(BUILDROOT)/%/.build-shell: $(BUILDROOT)/%/$(TARBALL) \
                       		 $(BUILDROOT)/%/Makefile
	@echo "-------------------------------------------------------------------"
	@echo "Building packages"
	@echo "-------------------------------------------------------------------"
	rm -rf $@
	cd $(dir $@) && \
	ls -l && \
	make PROJECT=$(PROJECT_PREFIX)$(PROJECT) NAME=$(NAME) \
		 TARBALL=$(TARBALL) TARGET=$(call ostarget,$(call osdist,$@)) \
		 VERSION=$($(call builderu,$@)_VERSION) \
		 RELEASE=$($(call builderu,$@)_RELEASE) \
		 NIGHTLY=$(NIGHTLY) COMMIT=$(CI_COMMIT)
	@echo "Successfully build $(PROJECT) for $@"
	ls -1sh $(dir $@)/results/
	test -f $(dir $@)/results/.done

# Generate Bintray descriptor.json
$(BUILDROOT)/%/descriptor.json: $(BUILDROOT)/%/descriptorfiles.json
	@mkdir -p $(dir $@)
	@echo "-------------------------------------------------------------------"
	@echo "Generating descriptor.json"
	@echo "-------------------------------------------------------------------"
	@echo '{' > $@.tmp
	@echo '    "package": {' >> $@.tmp
	@echo '        "name": "$(PROJECT)",' >> $@.tmp
ifneq ($(CI_TAG), )
	@echo '        "repo": "$(call builder,$@)",' >> $@.tmp
else
	@echo '        "repo": "$(call builder,$@)-nightly",' >> $@.tmp
endif
	@echo '        "subject": "tano-si"' >> $@.tmp
	@echo '    },' >> $@.tmp
	@echo '' >> $@.tmp
	@echo '    "version": {' >> $@.tmp
	@echo '        "name": "$(VERSION)",' >> $@.tmp
	@echo '        "released": "$(DATE)",' >> $@.tmp
ifneq ($(CI_TAG), )
	@echo '        "vcs_tag": "$(CI_TAG)",' >> $@.tmp
endif
	@echo '        "gpgSign": true' >> $@.tmp
	@echo '    },' >> $@.tmp
	@echo '' >> $@.tmp

	cat $(dir $@)/descriptorfiles.json >> $@.tmp

	@echo '' >> $@.tmp
	@echo '    "publish": true' >> $@.tmp
	@echo '}' >> $@.tmp
	@mv $@.tmp $@

# Generate Bintray descriptor.json files for deb
$(BUILDROOT)/deb-%/descriptorfiles.json:
	@mkdir -p $(dir $@)
	@echo '    "files": [{' >> $@.tmp
	@echo '        "includePattern": "packaging/root/deb-$(call osdist,$@)/results/(.*\.deb)",' >> $@.tmp
	@echo '        "uploadPattern": "$$1",' >> $@.tmp
	@echo '        "matrixParams": {' >> $@.tmp
	@echo '            "deb_distribution": "$(call ostarget,$(call osdist,$@))",' >> $@.tmp
	@echo '            "deb_component": "main",' >> $@.tmp
	@echo '            "deb_architecture": "$(call osarch,$(call osdist,$@))"' >> $@.tmp
	@echo '        }' >> $@.tmp
	@echo '    }],' >> $@.tmp
	@mv $@.tmp $@

# Generate Bintray descriptor.json files for apple
$(BUILDROOT)/apple-%/descriptorfiles.json:
	@mkdir -p $(dir $@)
	@echo '    "files": [{' >> $@.tmp
	@echo '        "includePattern": "packaging/root/apple-$(call osdist,$@)/results/(.*\.zip)",' >> $@.tmp
	@echo '        "uploadPattern": "/$$1"' >> $@.tmp
	@echo '    }],' >> $@.tmp
	@mv $@.tmp $@


##
## DEB
##

# Copy debian/ to buildroot/$OS-$DIST
$(BUILDROOT)/deb-%/debian/changelog: debian/changelog
	@mkdir -p $(abspath $(dir $@)/../)
	cp -fpR debian $(abspath $(dir $@)/../)

# A rule to build DEB packages
$(BUILDROOT)/deb-%/results/.done: $(BUILDROOT)/deb-%/debian/changelog \
                                  $(BUILDROOT)/deb-%/descriptor.json \
                                  $(BUILDROOT)/deb-%/.build
	@true


##
## Apple
##

# A rule to build Apple packages
$(BUILDROOT)/apple-%/results/.done: $(BUILDROOT)/apple-%/descriptor.json \
                                    $(BUILDROOT)/apple-%/.build-shell
	@true

##
## Targets
##

tarball: $(BUILDROOT)/$(TARBALL)

# Don't remove all rules, otherwise pattern matching will stop work
debian-%: $(BUILDROOT)/deb-debian-%/results/.done
	@true
ubuntu-%: $(BUILDROOT)/deb-ubuntu-%/results/.done
	@true
macos-%: $(BUILDROOT)/apple-macos-%/results/.done
	@true

clean:
	#rm -rf $(BUILDROOT)

.SECONDARY: # no target is removed because it is considered intermediate
.PHONY: clean
